﻿using Microsoft.EntityFrameworkCore;
using SovaDataService.SoModels;
using System.Collections.Generic;
using System.Linq;

namespace SovaDataService.SoDataServices
{
    public class AnswerDataService
    {
        /**
        * Retrieves all answers.
        */
        public IEnumerable<Answer> GetAll()
        {
            using (var db = new DbContext())
            {
                IQueryable<Answer> answers = db.Answers
                    .Include(a => a.Author)
                    .OrderBy(an => an.Id);
                return answers.ToList();
            }
        }

        /**
        * Retrieves an answers for a given id.
        */
        public Answer GetOne(int id)
        {
            using (var db = new DbContext())
            {
                IQueryable<Answer> answer = db.Answers
                    .Where(a => a.Id == id)
                    .Include(a => a.Comments);
                return answer.SingleOrDefault();
            }
        }

        /**
        * Retrieves all answers for a given question.
        */
        public IEnumerable<Answer> GetAnswersForQuestion(int questionId)
        {
            using (var db = new DbContext())
            {
                IQueryable<Answer> answers = db.Answers
                    .Where(an => an.QuestionId == questionId)
                    .Include(q => q.Question)
                    .OrderBy(an => an.Id);
                return answers.ToList();
            }
        }

        /**
         * Retrieves the total without having to fetch all the answers from db.
         */
        public int GetCount()
        {
            using (var db = new DbContext())
            {
                return db.Answers.Count();
            }
        }
    }
}
